C++ Basics

Do-While structure

Do-While statement behaves exactly like the while statement, the difference being that first, the statements between the braces are executed even if the condition is false from the beginning. This is useful when we want to execute the code at least once and only after that check some condition.

General syntax:

do
{
    Execute statements
}while(a_condition_is_true);

Note: Do not forget the semicolon (;) character after the brace.

Practical example (console menu):

#include <iostream>
int main()
{
    int option = 5;
    do
    {
        std::cout << "1. First menu option" << std::endl;
        std::cout << "2. Second menu option" << std::endl;
        std::cout << "3. Third menu option" << std::endl;
        std::cout << "4. Fourth menu option" << std::endl;
        std::cout << "5. Exit" << std::endl;
        std::cout << "Please enter an option: ";
        std::cin >> option;
    }while(option != 5);
}

The example above displays the menu even though the value of option variable is 5.